/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import entidade.controller.JPA.ProdutoJpaController;
import entidade.persistencia.Produto;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import javax.faces.context.FacesContext;
import javax.imageio.ImageWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author victorinox
 */
public class FileServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Integer prodId = Integer.parseInt(request.getParameter("produtoId"));
        
        OutputStream out = response.getOutputStream();

        ProdutoJpaController jpaController = ProdutoJPAInstance.getInstance().getJpaController();
        
        if(jpaController == null){
            return;
        }
        Produto prod = jpaController.findProduto(prodId);
        if(prod == null){
            return;
        }
        byte[] image = prod.getImagem();
        if(image == null){
            return;
        }

        File f = new File("img_temp_" + prodId + ".jpg");

        response.setContentType("image/jpeg");
        response.setContentLength(image.length);
        response.setHeader("Content-Disposition", "attachement; filename=\"" + f.getName() + "\"");
        out.write(image);
        out.flush();
        out.close();
        response.flushBuffer();
    }
}
